package com.tiny.base.factory;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * 封装Jest客户端的工厂类
 */
public class EsClientFactoryBean implements FactoryBean<JestClient>, DisposableBean, InitializingBean {

    private JestClient jestClient;

    /**
     * Es服务器的Url
     */
    private String url;

    private int connTimeout = 3000;

    private int readTimeout = 3000;

    public void destroy() {
        if(jestClient != null)
            jestClient.shutdownClient();
    }

    @Override
    public JestClient getObject() throws Exception {
        return jestClient;
    }

    @Override
    public Class<?> getObjectType() {
        return JestClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet(){
        JestClientFactory factory = new JestClientFactory();
        HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(getUrl()).multiThreaded(true)
                .connTimeout(getConnTimeout()).readTimeout(getReadTimeout()).build();
        factory.setHttpClientConfig(httpClientConfig);
        this.jestClient = factory.getObject();
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getConnTimeout(){
        return connTimeout;
    }

    public int getReadTimeout() {
        return readTimeout;
    }
}
